#include "napi/native_api.h"
#include <unicode/uidna.h>
#include <unicode/ustring.h>
#include <cstring>

static napi_value IDNtoASCII(napi_env env, napi_callback_info info)
{
    size_t argc = 1;
    napi_value args[1] = {nullptr};

    // Get function arguments
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    // Check if we have at least one argument
    if (argc < 1) {
        napi_throw_error(env, nullptr, "IDNtoASCII requires at least one argument");
        return nullptr;
    }

    // Check if argument is a string
    napi_valuetype valuetype;
    napi_typeof(env, args[0], &valuetype);
    if (valuetype != napi_string) {
        napi_throw_type_error(env, nullptr, "Argument must be a string");
        return nullptr;
    }

    // Get string length
    size_t str_length;
    napi_get_value_string_utf8(env, args[0], nullptr, 0, &str_length);

    // Allocate buffer and get string value
    char* input_str = new char[str_length + 1];
    napi_get_value_string_utf8(env, args[0], input_str, str_length + 1, &str_length);

    // Convert UTF-8 to UTF-16 for ICU
    UChar u_input[256];
    int32_t u_input_length = 0;
    UErrorCode status = U_ZERO_ERROR;
    u_strFromUTF8(u_input, 256, &u_input_length, input_str, str_length, &status);

    delete[] input_str;

    if (U_FAILURE(status)) {
        napi_throw_error(env, nullptr, "Failed to convert input to Unicode");
        return nullptr;
    }

    // Create UIDNA instance
    UIDNA* uidna = uidna_openUTS46(UIDNA_DEFAULT, &status);
    if (U_FAILURE(status)) {
        napi_throw_error(env, nullptr, "Failed to create UIDNA instance");
        return nullptr;
    }

    // Convert IDN to ASCII (Punycode)
    UChar u_output[256];
    UIDNAInfo info_output = UIDNA_INFO_INITIALIZER;
    int32_t output_length = uidna_nameToASCII(
        uidna,
        u_input,
        u_input_length,
        u_output,
        256,
        &info_output,
        &status
    );

    uidna_close(uidna);

    if (U_FAILURE(status) || info_output.errors != 0) {
        napi_throw_error(env, nullptr, "Failed to convert IDN to ASCII");
        return nullptr;
    }

    // Convert UTF-16 result back to UTF-8
    char output_str[256];
    int32_t output_str_length = 0;
    status = U_ZERO_ERROR;
    u_strToUTF8(output_str, 256, &output_str_length, u_output, output_length, &status);

    if (U_FAILURE(status)) {
        napi_throw_error(env, nullptr, "Failed to convert result to UTF-8");
        return nullptr;
    }

    // Create result string
    napi_value result;
    napi_create_string_utf8(env, output_str, output_str_length, &result);

    return result;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "idnToASCII", nullptr, IDNtoASCII, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "library",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterLibraryModule(void)
{
    napi_module_register(&demoModule);
}
